<template>
	<scroll-view scroll-y="true" class="msg-page" >
		<u-swipe-action
			:options="swipeOptions"
			v-for="(item,index) in msgs" :key="item.to"
			:show="item.showAction" :index="index"
			@click="clickAction"
			@open="openAction"
		>
			<messageItem :item="item.lastMsg" :num="item.unread"></messageItem>
		</u-swipe-action>
		<u-empty text="消息为空" mode="list" v-if="msgs.length==0"></u-empty>
	</scroll-view>
</template>

<script>
export default {
	data(){
		return {
			swipeOptions: [
				{
					text: '置顶',
					style: {
						backgroundColor: '#007aff'
					}
				},
				{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}
			],
			msgs:[]
		}
	},
	onShow(){
		const that=this
		const nim=getApp().globalData._nimInstance
		if(nim){
			console.log('setOptions',nim)
			nim.setOptions({
				onmsg:that.nimMsg,
				onroamingmsgs:that.nimRoamingMsgs,
				onofflinemsgs:that.nimOfflineMsgs,
				onsessions:that.nimSessions
			})
			nim.getLocalSessions({
			    limit: 100,
			    done: that.getLocalSessionsDone
			})
			nim.getServerSessions({
				//minTimestamp: 1571039417853, // 获取 1571039417853 时间之后更新的会话，增量获取
				//maxTimestamp: 1571039418800, // 非第一页，上一页会话列表最小的时间时1571039418800
				done: function (error, obj) {
					 console.log('获取会话列表' + (!error?'成功':'失败'), error, obj);
				}
			});
		}
	},
	methods:{
		nimMsg(msg){
			console.log('nimMsg',msg)
			let findMsg=this.msgs.filter(item => item.to==msg.to)
			if(findMsg.length>0){
				findMsg[0].lastMsg=msg
				findMsg[0].unread++
			}else{
				this.msgs.push({
					lastMsg:msg,
					showAction:false,
					to:msg.to,
					unread:1
				})
			}
			
		},
		
		nimRoamingMsgs(msg){
			console.log('nimRoamingMsgs',msg)
		},
		
		nimOfflineMsgs(msg){
			console.log('nimOfflineMsgs',msg)
		},
		
		nimSessions(sessions){
			console.log('nimSessions',sessions)
		},
		
		//获取本地会话列表
		getLocalSessionsDone(error, obj){
			console.log('获取本地会话列表' + (!error?'成功':'失败'));
			if (!error) {
				console.log(obj.sessions)
				this.msgs=[]
				obj.sessions.map(item => {
					item.showAction=false
					this.msgs.push(item)
				})
			}
		},
		
		clickAction(index,index1){
			if(index1 == 1) {
				this.msgs.splice(index, 1);
				this.$u.toast(`删除了第${index}个cell`);
			} else {
				this.$u.toast(`收藏成功`);
			}
		},
		
		openAction(index) {
			// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
			// 原本为'false'，再次设置为'false'会无效
			console.log(index)
			this.msgs[index].showAction = true;
			this.msgs.map((val, idx) => {
				if(index != idx) val.showAction = false;
			})
		}
		
	}
}
</script>

<style lang="scss">
.msg-page{
	padding: 20rpx 0rpx;
	width: 100vw;
	box-sizing: border-box;
}
</style>
